const { SerialPort } = require('serialport')

const store = {
  hubInfo: null,
  hub: null,
}

kickStarter()

function kickStarter () {
  SerialPort.list().then(hubFinder)
}

function hubFinder (ports) {
  store.hubInfo = (ports || []).find(
    (port) => port.manufacturer === 'Joraver LTD'
  ) || null

  if (!store.hubInfo) {
    console.log(new Date())
    console.log('==== Хаб с признаком "manufacturer=Joraver LTD" не присоединен')
    setTimeout(kickStarter, 1000)

    return
  }

  hubOpener()
}

function hubOpener() {
  if (store.hub?.isOpen) {
    store.hub.close()
  }

  showHubInfo()

  const options = {
    path: store.hubInfo.path,
    baudRate: 115200,
  }

  store.hub = new SerialPort(options, afterHubTryOpen)
}

function afterHubTryOpen (error) {
  if (error) {
    console.log('OPEN PORT Error: ', error)
    setTimeout(hubProbe, 1000)
  } else {
    hubSetupActions()
  }
}

function hubSetupActions () {
  store.hub.on('data', dataParser)

  store.hub.on('error', (error) => {
    console.log('ON ERROR', error)
    kickStarter ()
  })

  regularQuery()
}


function dataParser (incoming) {
  const buf = Array.from(incoming)

  if (buf[1] === 253) {
    console.log(new Date())
    console.log('ТРЕВОГА!!!', incoming)
  } else {
    console.log(incoming)
  }
}

const commands = [
  [2, 1, 0, 0],
  [3, 1, 0, 0],
]

function regularQuery (index = 0) {
  if (!index) {
    console.log('---------------------')
  }

  const command = commands[index];

  if (command) {
    if (!store.hub?.isOpen) {
      kickStarter()

      return
    }

    const buffer = Buffer.from(command)
    console.log('>>>Запрос:', buffer)
    store.hub.write(buffer)

    setTimeout(() => {
      regularQuery(index + 1)
    }, 50)
  } else {
    setTimeout(regularQuery, 500)
  }
}

function showHubInfo () {
  // hubInfo = {
  //   path: "/dev/ttyACM0",
  //   manufacturer: "Joraver LTD",
  //   serialNumber: "5D6F22873932",
  //   pnpId: "usb-Joraver_LTD_Antifire_System_HUB_5D6F22873932-if00",
  //   locationId: undefined,
  //   vendorId: "1e61",
  //   productId: "5740"
  // }
  console.log('==== Хаб системы обнаружен')

  Object.keys(store.hubInfo).forEach(
    (attr) => console.log('--', { [attr]: store.hubInfo[attr] })
  )
}
